package com.seed.core.builder.declare;

import com.seed.core.column.Column;
import com.seed.core.enumeration.PropertyType;
import com.seed.core.pojo.Const;
import com.seed.core.pojo.seed.Relation;
import com.seed.core.pojo.seed.Seed;
import com.seed.core.query.pojo.Declared;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class QueryDeclaredBuilder extends DeclaredBuilder {
    public QueryDeclaredBuilder(Seed seed, List<String> values) {
        super(seed, values);
    }

    public Map<String, Declared> build() {
        Map<String, Declared> ret = super.build();
        addExtraDeclared(seed, ret);

        return ret;
    }

    /**
     * 补充未声明的ID列
     * @param seed 模块
     * @param declareds 申明
     */
    private void addExtraDeclared(Seed seed, Map<String, Declared> declareds) {
        Map<String, Column> columns = seed.getColumns();
        Set<String> keySet = declareds.keySet();
        if(!keySet.contains(Const.ID) && columns.get(Const.ID) != null) {
            declareds.put(Const.ID, new Declared(columns.get(Const.ID)));
        }
        if(!keySet.contains(Const.VERSION) && columns.get(Const.VERSION) != null) {
            declareds.put(Const.VERSION, new Declared(columns.get(Const.VERSION)));
        }

        for(Map.Entry<String, Declared> entry: declareds.entrySet()) {
            Declared declared = entry.getValue();
            PropertyType propertyType = declared.getType();
            switch (propertyType) {
                case hasOne, belongsTo, hasMany, habtm -> {
                    Seed targetSeed = ((Relation) declared.getProperty()).targetSeed();
                    addExtraDeclared(targetSeed, declared);
                }
            }
        }
    }
}
